﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using GYCTOAManagementSystemNewApi.Controllers;
using GYCTOAManagementSystemNewApi.Controllers.PublicController;
using GYCTOAManagementSystemNewApi.Model;
using GYCTOAManagementSystemNewApi.Model.Enum;
using GYCTOAManagementSystemNewApi.Model.Tool;
using GYCTOAManagementSystemNewApi.Model.ViewModel;
using GYCTOAManagementSystemNewApi.Public;
using GYCTOAManagementSystemNewApi.Tool;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace GYCTOAManagementSystemNewApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController :Controller
    {
        DBContext db;
        Message mes;
        GlobalPublic globalPublic;
        public LoginController(DBContext _db, Message _mes, GlobalPublic _globalPublic)
        {
            db = _db;
            mes = _mes;
            globalPublic = _globalPublic;
        }
        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="username">手机号、身份证号、工号之一</param>
        /// <param name="password">密码：未加密</param>
        /// <returns></returns>
        [HttpGet("Login")]
        public JsonResult Login(string username, string password)
        {
            var headurl = "";
            TokenManage token = new TokenManage();
            string passwordMD5 = MD5Encrypt.Encrypt(password);
            var a = db.Users.ToList();
            Users user = db.Users.Where(l => (l.Phone == username || l.JobNumber == username || l.Card == username) && (l.Password == passwordMD5|| l.Password == password) && (l.InternshipState != (int)InternshipStateEnum.Quit) && !l.Delete).FirstOrDefault();
            if (user == null)
            {
                mes.IsSuccess = false;
                mes.Msg = globalPublic.GetDescription(MessageTextEnums.ErrorAccount);
            }
            else
            {
                //获取人员相关角色
                string[] roleids = user.RoleId.Split(',');
                List<string> strRoleNumber = new List<string>();
                foreach (var item in roleids)
                {
                    var RoleNumber = db.Role.Find(Convert.ToInt32(item)).RoleNumber;
                    if (! string.IsNullOrEmpty(RoleNumber))
                    {
                        var numberaray = RoleNumber.Split(',');
                        foreach (var itemval in numberaray)
                        {
                            if (!(strRoleNumber.Contains(itemval)))
                            {
                                strRoleNumber.Add(itemval);
                            }
                        }
                    }
                }
                strRoleNumber = strRoleNumber.Distinct().Where(x => !string.IsNullOrEmpty(x)).ToList();
                var tok = token.CreateToken(user, string.Join(",", string.Join(',',strRoleNumber)));
                mes.IsSuccess = true;
                mes.Msg = tok;
                //string headportrait = Path.GetPathRoot(AppDomain.CurrentDomain.BaseDirectory) + PublicMethodApiController.FileloadStr + "/1/" + (int)FileTypeEnum.UserFile + "/" + user.Id + "/3";
                //var filename = IsExistenceFile(headportrait);
                //if (!IsExistenceFile(headportrait).Equals(""))
                //{
                //    headurl = "/OAFile/" + (int)FileTypeEnum.UserFile + "/" + user.Id + "/3/" + filename;
                //}
            }
            //PublicTool.gettoken();//获取钉钉接口认证数据
            return new JsonResult(new { msgDB = mes, UserInfo = user });
        }

        /// <summary>
        /// 判断头像是否存在,存在返回文件名称
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        [HttpPost("IsExistenceFile")]
        public string IsExistenceFile(string url)
        {
            var filename = "";
            bool result = System.IO.Directory.Exists(url);
            if (result)
            {
                filename = Directory.GetFiles(url).FirstOrDefault();
                FileInfo info = new FileInfo(filename);
                filename = info.Name;
            }
            return filename;
        }

        /// <summary>
        /// 获取目录数据
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetMenu")]
        public JsonResult GetMenu()
        {
            var roleLiost = db.rolemenu.Where(x => !x.Delete).ToList();
            List<rolemenu> viewrolemenu = new List<rolemenu>();
            foreach (var item in roleLiost)
            {
                if (item.ParentId == "0")
                {
                    foreach (var ite in roleLiost)
                    {
                        if (ite.ParentId == item.Roid)
                        {
                            item.children.Add(ite);
                        }
                    }
                    viewrolemenu.Add(item);
                }

            }
            return new JsonResult(new { menu = viewrolemenu });
        }
        /// <summary>
        /// 增加目录
        /// </summary>
        /// <returns></returns>
        [HttpPost("AddMenu")]
        public JsonResult AddMenu([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            //int userId = Convert.ToInt32(jsondata["finance"]);
            //(FinanceReimbursement finance, List<FinanceDocDetail> financeDocDetails, bool IsFinishReversal)
            rolemenu rolemenudb = JsonConvert.DeserializeObject<rolemenu>(jsondata["Addrolemenu"].ToString());
            db.Add(rolemenudb);
            var bit = db.SaveChanges() > 0;
            return new JsonResult(new { bit = bit });
        }

    }
}